<?php
/**
 * 周舟 hzboye010@163.com
 * addby sublime snippets
 */
namespace app\index\domain;

use app\index\domain\BaseDomain;
use app\bbs\api\FilterKeyWordsApi;
use app\bbs\api\ForumPostLikeApi;
use app\bbs\api\ForumAttachmentApi;
use app\bbs\api\ForumForumApi;
use app\bbs\api\ForumPostApi;
use app\bbs\api\ForumThreadApi;
use app\bbs\api\ForumSilentApi;
use app\bbs\api\VPostAndCommentApi;
use app\bbs\model\ForumPostLike;
use app\bbs\model\ForumAdmingroup;
use app\bbs\api\ForumUserAdmingroupApi;
use app\bbs\model\ForumPost;
use app\shop\api\FavoritesApi;
use app\bbs\api\BbsMemberApi;
use app\bbs\api\TagApi;
use app\system\api\MemberApi;
use app\system\api\BabyApi;
use app\system\api\MemberFocusApi;
use app\admin\api\MessageApi;
use app\admin\model\Message;
use app\system\api\UserLogApi;

class ForumThreadDomain extends BaseDomain{

    protected $business_code = 'forumThread';
    /**
     * 假删除
     */
    public function delete(){
        $this->checkVersion(101);
        addLog("ForumThread/delete", $_GET, $_POST, $this->client_id . "调用帖子删除接口!");

        if(IS_POST){

            $tid = $this -> _post('tid',"",'缺少tid参数');
            $uid = $this -> _post('uid',"",'用户id缺失');
            //帖子删除状态  板块帖子数-1
            $result = apiCall(ForumThreadApi::DELETE,[$tid,$uid]);
            if($result['status']){
                //-score  -exp
                $r = apiCall(UserLogApi::THREAD_DELETE,[$uid]);
                if(!$r['status']) $this ->apiReturnErr($r['info']);
                $this -> apiReturnSuc(['info'=>$result['info'],'msg'=>$r['info']]);
            }else{
                $this -> apiReturnErr($result['info']);
            }

        }


    }
    //收藏分页查询
    public function getFavorites(){
        $this->checkVersion($this->api_ver);
        addLog("ForumThread/favorites", $_GET, $_POST, $this->client_id . "调用收藏帖子分页接口!");

        if(IS_POST){

            $type      = 2;//帖子
            $uid       = $this -> _post('uid',0,'用户id缺失');
            $fid       = $this -> _post('fid',0);
            $page_no   = $this -> _post('page_no',1);
            $page_size = $this -> _post('page_size',10);
            $img_num   = $this -> _post('img_num',3);
            $max_like  = $this -> _post('max_like',10);
            $max_reply = $this -> _post('max_reply',3);
            $max_comment = $this -> _post('max_comment',2);

            $page = ['curpage' =>$page_no,'size'    =>$page_size];
            $map  = ['uid'  => $uid,'type' => $type];
            if($fid){
                $r = apiCall(ForumForumApi::GET_FID_WITH_CHILD,[$fid]);
                if(!$r['status']) return $this->apiReturnErr($r['info']);
                if($r['info']) $map['_string'] = 'fid in ('.implode(',', $r['info']).')';
            }
            $result = apiCall(FavoritesApi::QUERY_THREAD_WITH_COUNT,[$map,$page]);
            if($result['status']){
                foreach($result['info']['list'] as &$v){

                    $time = time() - $v['dateline'];
                    $v['dateline_show'] = getDateInfo($time,$v['dateline']);
                    //查询用户信息
                    // $v['user_info'] = $this->getUserInfo($v['author_id']);
                    $userInfo    = $this->getUserInfo($v['author_id']);
                    $v['head']   = !empty($userInfo) ? $userInfo['head'] : '';
                    $v['author'] = !empty($userInfo) ? $userInfo['nickname'] : '';
                    $v['sex']    = !empty($userInfo) ? $userInfo['sex'] : '';
                    //查询附件信息
                    $res = apiCall(ForumAttachmentApi::QUERY_NO_PAGING,[['tid' => $v['tid'],'pid'=>0],false,"aid"]);
                    if(!$res['status']) $this -> apiReturnErr($res['info']);
                    $v['img'] = [];
                    $i = 0;
                    foreach($res['info'] as $vv){
                        array_push($v['img'],$vv['aid']);
                        $i++;
                        if($i >= $img_num) break;
                    }
                    $v['img_test'] = $i.':'.$img_num;
                    // trace($v);
                    $v['is_like']  = '0';
                    $v['is_fav']   = '0';
                    $v['is_focus'] = '0';
                    // unset($v['position']);
                    if($uid){
                        //用户是否点赞
                        $map = ['tid'=>$v['tid'],'uid'=>$uid];
                        $res = apiCall(ForumPostLikeApi::COUNT,[$map]);

                        if(!$res['status']) $this->apiReturnErr($res['info']);
                        $v['is_like'] = intval($res['info'])?'1':'0';
                        //用户是否收藏
                        $map = [
                            'uid'         => $uid,
                            'type'        => 2,
                            'favorite_id' => $v['tid'],
                        ];
                        $res = apiCall(FavoritesApi::GET_INFO,[$map]);
                        if(!$res['status']) $this -> apiReturnErr($res['info']);
                        if(!empty($res['info'])) $v['is_fav'] = '1';
                        //用户是否关注
                        $map = [
                            'type'        => 2,
                            'favorite_id' => $v['tid'],
                        ];
                        $v['is_focus'] = apiCall(MemberFocusApi::IS_FOCUS,[$uid,$v['author_id']]);
                    }
                    //点赞信息
                    $v['like_info'] = [];
                    if(intval($max_like)>0){
                        $r = apiCall(ForumPostLikeApi::QUERY_WITH_USER,[['p.tid'=>$v['tid']],['curpage'=>1,'size'=>$max_like],'p.`like_time` desc',false,'p.id,p.uid,p.like_time,m.head,m.nickname']);
                        if(!$r['status']) $this->apiReturnErr($r['info']);
                        $v['like_info'] = $r['info']['list'];
                    }
                    //标签信息
                    $v['tag_info'] = apiCall(TagApi::GET_S,[$v['tid']]);
                    //宝宝信息
                    $v['baby_default'] = apiCall(BabyApi::GET_DEFAULT,[$v['author_id']]);
                     //获取回复信息 - 自带评论
                    $v['reply_info']= [];
                    if(intval($max_reply)){
                        $res = apiCall(ForumPostApi::QUERY_POST,array($v['fid'],$v['tid'],1,$max_reply,$max_comment,0));
                        if(!$res['status']) $this -> apiReturnErr($res['info']);
                        $v['reply_info'] = $res['info'];
                        //修复 回复数错误
                        if($res['info'] && intval($res['info']['count']) !== intval($v['replies'])) $v['replies'] = $res['info']['count'];
                    }
                }

                $this -> apiReturnSuc($result['info']);
            }else{
                $this -> apiReturnErr($result['info']);
            }

        }

    }

    //帖子 收藏
    public function favorites(){
        $this->checkVersion($this->api_ver);
        addLog("ForumThread/favorites", $_GET, $_POST, $this->client_id . "调用主题帖收藏接口!");

        if(IS_POST){

            $tid = $this -> _post('tid',-1,'缺少tid参数');
            $uid = $this -> _post('uid',-1,'缺少uid参数');
            $favorite_value = $this -> _post('favorite_value',-1,'缺少favorite_value参数');

            $type = 2;//收藏帖子
            $map = [
                'uid'         => $uid,
                'favorite_id' => $tid,
                'type'        => $type,
            ];

            $result = apiCall(FavoritesApi::GET_INFO,array($map));
            if(!$result['status']) $this -> apiReturnErr($result['info']);
            if($favorite_value == 1){
                if(!empty($result['info'])){
                    //已经存在收藏信息
                    $this -> apiReturnErr('该收藏已存在!');
                }
                $map = [
                    'tid' => $tid
                ];
                $result = apiCall(ForumThreadApi::GET_INFO,array($map));
                if(!$result['status']) $this -> apiReturnErr($result['info']);
                if(empty($result['info'])) $this -> apiReturnErr('此帖还未出生');
                $favorite_content = json_encode($result['info']);

                $entity = [
                    'uid'              => $uid,
                    'type'             => 2,
                    'favorite_id'      => $tid,
                    'create_time'      => time(),
                    'favorite_content' => $favorite_content,
                ];
                $result = apiCall(FavoritesApi::ADD,[$entity]);
                if($result['status']){
                    //收藏数 +1
                    apiCall(ForumThreadApi::SET_INC,[['tid'=>$tid],'favs',1]);
                    $this -> apiReturnSuc('收藏成功');
                }else{
                    $this -> apiReturnErr($result['info']);
                }

            }else if($favorite_value == 0){
                if(empty($result['info'])){
                    //不存在收藏信息
                    $this -> apiReturnErr('您还未收藏该帖!');
                }
                $id = $result['info']['id'];
                $map = array(
                    'id' => $id,
                );
                $result = apiCall(FavoritesApi::DELETE,array($map));
                if($result['status']){
                    //收藏数-1
                    apiCall(ForumThreadApi::SET_DEC,[['tid'=>$tid],'favs',1]);
                    $this -> apiReturnSuc('取消收藏成功！');
                }else{
                    $this -> apiReturnErr($result['info']);
                }

            }else{
                $this -> apiReturnErr('favorite_value参数错误');
            }

        }

    }

    //详情
    public function detail(){
        $this->checkVersion($this->api_ver);
        addLog("ForumThread/detail", $_GET, $_POST, $this->client_id . "调用论坛帖子详情接口!");

        if(IS_POST){
            $uid = $this -> _post('uid','');
            $tid = $this -> _post('tid','','帖子id缺失');
            $max_reply   = $this -> _post('max_reply',3);
            $max_comment = $this -> _post('max_comment',2);
            $max_img     = $this -> _post('max_img',99);
            $max_like    = $this -> _post('max_like',10);

            $map = ['tid' => $tid];
            $result = apiCall(ForumThreadApi::GET_INFO,[$map]);
            if($result['status']){
                if(empty($result['info'])) $this->apiReturnSuc($result['info']);
                //帖子查看数 +1
                apiCall(ForumThreadApi::SET_INC,[$map,'views']);
                if(-1 == $result['info']['status']) $this->apiReturnErr('该帖已经删除');
                //查询帖子收藏信息
                $result['info']['is_fav']   = '0';
                $result['info']['is_like']  = '0';
                $result['info']['is_focus'] = '0';
                if(!empty($uid)){
                    $map = [
                        'uid'         => $uid,
                        'type'        => 2,
                        'favorite_id' => $tid,
                    ];
                    $res = apiCall(FavoritesApi::GET_INFO,[$map]);
                    if(!$res['status']) $this -> apiReturnErr($res['info']);
                    if(!empty($res['info'])) $result['info']['is_fav'] = 1;
                    $map = [
                        'tid'   =>$tid,
                        'uid'   =>$uid
                    ];
                    $res = apiCall(ForumPostLikeApi::COUNT,[$map]);
                    if(!$res['status']) $this->apiReturnErr($res['info']);
                    if($res['info']>0) $result['info']['is_like'] = '1';
                    //查询用户是否关注作者
                    $result['info']['is_focus'] = apiCall(MemberFocusApi::IS_FOCUS,[$uid,$result['info']['author_id']]);

                }
                //点赞信息
                $result['info']['like_info'] = [];
                if(intval($max_like)>0){
                    $r = apiCall(ForumPostLikeApi::QUERY_WITH_USER,[['p.tid'=>$tid],['curpage'=>1,'size'=>$max_like],'p.`like_time` desc',false,'p.id,p.uid,p.like_time,m.head,m.nickname']);
                    if(!$r['status']) $this->apiReturnErr($r['info']);
                    $result['info']['like_info'] = $r['info']['list'];
                }
                //查询作者宝宝信息
                $result['info']['baby_default'] = apiCall(BabyApi::GET_DEFAULT,[$result['info']['author_id']]);
                //查询帖子标签信息
                $res = apiCall(TagApi::GET_S,[$tid]);
                $result['info']['tag_info'] = $res;
                //查询帖子附件信息
                $res = apiCall(ForumAttachmentApi::QUERY_NO_PAGING,array(['tid'=>$tid,'pid'=>0],false,"aid"));
                if($res['status']){
                    $result['info']['img'] = [];
                    $i = 0;
                    foreach($res['info'] as $v){
                        array_push($result['info']['img'],$v['aid']);
                        $i++;
                        if($i>= $max_img) break;
                    }
                    // $this->apiReturnErr($result['info']['img']);
                }else{
                    $this -> apiReturnErr($res['info']);
                }
                //查询作者信息
                $userInfo = $this->getUserInfo($result['info']['author_id']);
                $result['info']['author'] = !empty($userInfo) ? $userInfo['nickname'] : '';
                $result['info']['head']   = !empty($userInfo) ? $userInfo['head'] : '';
                $result['info']['sex']    = !empty($userInfo) ? $userInfo['sex'] : '';
                $result['info']['group']  = !empty($userInfo) ? $userInfo['group'] : [];
                //获取回复信息 - 自带评论
                $r = apiCall(ForumPostApi::QUERY_POST,array($result['info']['fid'],$tid,1,$max_reply,$max_comment,0));
                if(!$r['status']) $this -> apiReturnErr($r['info']);
                $result['info']['reply_info'] = $r['info'];
                //修复 回复数错误
                $count = $r['info'] ? $r['info']['count']:0;
                $result['info']['replies'] = max($result['info']['replies'],$count);
                $this -> apiReturnSuc($result['info']);
            }else{
                $this -> apiReturnErr($result['info']);
            }
        }
    }

    //tag分页查询
    public function tag(){
        //status -1删除 1审核 0正常 //TODO 禁止回复
        $this->checkVersion($this->api_ver);
        addLog("ForumThread/tag", $_GET, $_POST, $this->client_id . "调用论坛主题查询接口!");

        if(IS_POST){
            $tag_id      = $this -> _post('tag_id',0,'tag_id缺失');
            $fid         = $this -> _post('fid',0);
            $uid         = $this -> _post('uid',0);
            $page_no     = $this -> _post('page_no',1);
            $page_size   = $this -> _post('page_size',10);
            $imgs        = $this -> _post('img_num',3);
            $max_reply   = $this -> _post('max_reply',3);
            $max_comment = $this -> _post('max_comment',2);
            $max_like    = $this -> _post('max_like',10);
            $fresh       = $this -> _post('fresh',0);

            $cacheKey = 'threadtag-'.$tag_id.'-'.$fid.'-'.$imgs.'-'.$max_like.'-'.$max_comment.'-'.$page_no.'-'.$page_size.'-'.$max_reply.'-'.$uid;
            $this->checkCache($cacheKey,$page_no,5,$fresh);

            $map         = [];
            if($fid )    $map['fid']    = intval($fid);
            if($tag_id)  $map['tag_id'] = $tag_id;
            if($imgs)    $map['imgs']   = intval($imgs);
            $result = apiCall(ForumThreadApi::QUERY_TAG,[$map,$page_no,$page_size,'dateline desc']);
            // trace('vvv--');
            // trace($result);
            if($result['status']){
                $list  = $result['info']['list'];
                $count = $result['info']['count'];
                foreach ($list as $k => &$v) {
                    // trace($v);
                    $v['is_like']  = '0';
                    $v['is_fav']   = '0';
                    $v['is_focus'] = '0';
                    unset($v['position']);
                    if($uid){
                        //用户是否点赞
                        $map = ['tid'=>$v['tid'],'uid'=>$uid];
                        $result = apiCall(ForumPostLikeApi::COUNT,[$map]);
                        if(!$result['status']) $this->apiReturnErr($result['info']);
                        $v['is_like'] = intval($result['info'])?'1':'0';
                        //用户是否收藏
                        $map = [
                            'uid'         => $uid,
                            'type'        => 2,
                            'favorite_id' => $v['tid'],
                        ];
                        $res = apiCall(FavoritesApi::GET_INFO,[$map]);
                        if(!$res['status']) $this -> apiReturnErr($res['info']);
                        if(!empty($res['info'])) $v['is_fav'] = 1;
                        //用户是否关注
                        $map = [
                            'type'        => 2,
                            'favorite_id' => $v['tid'],
                        ];
                        $v['is_focus'] = apiCall(MemberFocusApi::IS_FOCUS,[$uid,$v['author_id']]);
                    }
                    //点赞信息
                    $v['like_info'] = [];
                    if(intval($max_like)>0){
                        $r = apiCall(ForumPostLikeApi::QUERY_WITH_USER,[['p.tid'=>$v['tid']],['curpage'=>1,'size'=>$max_like],'p.`like_time` desc',false,'p.id,p.uid,p.like_time,m.head,m.nickname']);
                        if(!$r['status']) $this->apiReturnErr($r['info']);
                        $v['like_info'] = $r['info']['list'];
                    }
                    //标签信息
                    $v['tag_info'] = apiCall(TagApi::GET_S,[$v['tid']]);
                    //宝宝信息
                    $v['baby_default'] = apiCall(BabyApi::GET_DEFAULT,[$v['author_id']]);
                    //获取回复信息 - 自带评论
                    $result = apiCall(ForumPostApi::QUERY_POST,array($v['fid'],$v['tid'],1,$max_reply,$max_comment,0));
                    if(!$result['status']) $this -> apiReturnErr($result['info']);
                    $v['reply_info'] = $result['info'];
                }
                $this -> cache($cacheKey,['count'=>$count,'list'=>$list]);
            }else{
                $this -> apiReturnErr($result['info']);
            }
        }
    }

    //分页查询
    public function queryBBL(){
        //status -1删除 1审核 0正常 //TODO 禁止回复
        $this->checkVersion($this->api_ver);
        addLog("ForumThread/queryBBL", $_GET, $_POST, $this->client_id . "调用宝宝乐帖子分页查询接口!");
        if(IS_POST){
            $fid       = 4; //宝宝乐
            $uid       = $this -> _post('uid','');
            // $digest    = $this -> _post('digest',-1);
            $page_no   = $this -> _post('page_no',1);
            $page_size = $this -> _post('page_size',10);
            // $title     = $this -> _post('title','');
            $imgs      = $this -> _post('img_num',3);
            $max_reply = $this -> _post('max_reply',3);
            $fresh     = $this -> _post('fresh',0);
            $max_like  = $this -> _post('max_like',10);

            $cacheKey  = 'froumThread-4-'.$uid.'-'.$page_no.'-'.$page_size.'-'.$imgs.'-'.$max_reply.'-'.$max_like;
            $this->checkCache($cacheKey,$page_no,10,$fresh);

            $order     = "dateline desc";
            $map = [];
            if(0 !== $fid )     $map['fid']   = intval($fid);
            // if($title)          $map['title'] = $title;
            // if(-1 !== $digest)  $map['digest']= intval($digest);
            if($imgs) $map['imgs']  = intval($imgs);
            $time1 = microtime(true);
            // $r = apiCall(ForumThreadApi::QUERY_WITH_COUNT,array($map,$map_invisible,$page,$order));
            $r = apiCall(ForumThreadApi::QUERY_PAGE,[$map,$page_no,$page_size,$order]);
            $time2 = microtime(true);
            if($r['status']){
                $list  = $r['info']['list'];
                $count = $r['info']['count'];
                foreach ($list as $k => &$v) {
                    // trace($v);
                    $v['is_like']  = '0';
                    // $v['is_fav']   = '0';
                    $v['is_focus'] = '0';
                    unset($v['position']);
                    if($uid){
                        //用户是否点赞
                        $map = ['tid'=>$v['tid'],'uid'=>$uid];
                        $res = apiCall(ForumPostLikeApi::COUNT,[$map]);
                        if(!$res['status']) $this->apiReturnErr($res['info']);
                        $v['is_like'] = intval($res['info']) ? '1':'0';
                        //用户是否收藏
                        // $map = [
                        //     'uid'         => $uid,
                        //     'type'        => 2,
                        //     'favorite_id' => $v['tid'],
                        // ];
                        // $res = apiCall(FavoritesApi::GET_INFO,[$map]);
                        // if(!$res['status']) $this -> apiReturnErr($res['info']);
                        // if(!empty($res['info'])) $v['is_fav'] = 1;
                        //用户是否关注
                        $map = [
                            'type'        => 2,
                            'favorite_id' => $v['tid'],
                        ];
                        $res = apiCall(MemberFocusApi::IS_FOCUS,[$uid,$v['author_id']]);
                        $v['is_focus'] = $res;
                    }
                    //点赞信息
                    $v['like_info'] = [];
                    if(intval($max_like)>0){
                        $r = apiCall(ForumPostLikeApi::QUERY_WITH_USER,[['p.tid'=>$v['tid']],['curpage'=>1,'size'=>$max_like],false,false,'p.id,p.uid,p.like_time,m.head,m.nickname,m.sex']);
                        if(!$r['status']) $this->apiReturnErr($r['info']);
                        $v['like_info'] = $r['info']['list'];
                    }
                    //标签信息
                    // $v['tag_info'] = apiCall(TagApi::GET_S,[$v['tid']]);
                    //宝宝信息
                    // $v['baby_default'] = apiCall(BabyApi::GET_DEFAULT,[$v['author_id']]);
                    //获取同级回复评论信息
                    $v['reply_info']= [];
                    if(intval($max_reply)){
                        $r = apiCall(VPostAndCommentApi::QUERY,[['tid'=>$v['tid']],['curpage'=>1,'size'=>$max_reply],'dateline asc']);
                        if(!$r['status']) $this->apiReturnErr($r['info']);
                        if(!empty($r['info']['list'])){
                        //TODO : optimize : 查询缓慢
                            foreach ($r['info']['list'] as &$vv) {
                                //查询用户信息
                                $uid2 = intval($vv['author_id']);
                                $userInfo     = $this->getUserInfo($uid2);
                                $vv['author'] = !empty($userInfo) ? $userInfo['nickname'] : '';
                                $vv['head']   = !empty($userInfo) ? $userInfo['head'] : '';
                                $vv['sex']    = !empty($userInfo) ? $userInfo['sex'] : '';
                                $uid2 = intval($vv['to_uid']);
                                $vv['to_uinfo'] = ['temp'=>''];//安卓占位符
                                if($uid2){
                                    $userInfo = $this->getUserInfo($uid2);
                                    $vv['to_uinfo']['nickname'] = !empty($userInfo) ? $userInfo['nickname'] : '';
                                    $vv['to_uinfo']['head'] = !empty($userInfo) ? $userInfo['head'] : '';
                                    $vv['to_uinfo']['sex'] = !empty($userInfo) ? $userInfo['sex'] : '';
                                }
                            }
                        }
                        $v['reply_info'] = $r['info'];
                        //修复 回复数错误
                        if($r['info'] && intval($r['info']['count']) !== intval($v['replies'])) $v['replies'] = $r['info']['count'];
                    }
                }
                $time3 = microtime(true);
                addLog('ForumThread/queryBBL/time',$time1.'-'.$time2.'-'.$time3,$time2-$time1,$time3-$time1);
                $this -> cache($cacheKey,['count'=>$count,'list'=>$list],120);
            }else{
                $this -> apiReturnErr($r['info']);
            }
        }
    }

    //分页查询
    public function query(){
        //status -1删除 1审核 0正常 //TODO 禁止回复
        $this->checkVersion($this->api_ver);
        addLog("ForumThread/query", $_GET, $_POST, $this->client_id . "调用论坛主题查询接口!");

        if(IS_POST){

            $fid       = $this -> _post('fid',0);
            $uid       = $this -> _post('uid',0);
            $digest    = $this -> _post('digest',-1);
            $page_no   = $this -> _post('page_no',1);
            $page_size = $this -> _post('page_size',10);
            $title     = $this -> _post('title','');
            $imgs      = $this -> _post('img_num',3);
            $max_reply = $this -> _post('max_reply',3);
            $max_comment = $this -> _post('max_comment',2);
            $max_like  = $this -> _post('max_like',10);
            $fresh     = $this -> _post('fresh',0);

            $cacheKey  = 'froumThread-'.$fid.'-'.$uid.'-'.$digest.'-'.$page_no.'-'.$page_size.'-'.$imgs.'-'.$max_reply.'-'.$max_comment.'-'.$max_like.'-'.$title;
            // $this->checkCache($cacheKey,$page_no,5,$fresh);

            $order     = "dateline desc";
            $map = [];
            if(0 !== $fid )     $map['fid']   = intval($fid);
            if($title)          $map['title'] = $title;
            if(-1 !== $digest)  $map['digest']= intval($digest);
            if($imgs)           $map['imgs']  = intval($imgs);
            // $result = apiCall(ForumThreadApi::QUERY_WITH_COUNT,array($map,$map_invisible,$page,$order));
            $result = apiCall(ForumThreadApi::QUERY_PAGE,[$map,$page_no,$page_size,$order]);
            // trace('vvv--');
            // trace($result);
            if($result['status']){
                $list  = $result['info']['list'];
                $count = $result['info']['count'];
                foreach ($list as $k => &$v) {
                    // trace($v);
                    $v['is_like']  = '0';
                    $v['is_fav']   = '0';
                    $v['is_focus'] = '0';
                    unset($v['position']);
                    if($uid){
                        //用户是否点赞
                        $map = ['tid'=>$v['tid'],'uid'=>$uid];
                        $result = apiCall(ForumPostLikeApi::COUNT,[$map]);

                        if(!$result['status']) $this->apiReturnErr($result['info']);
                        $v['is_like'] = intval($result['info'])?'1':'0';
                        //用户是否收藏
                        $map = [
                            'uid'         => $uid,
                            'type'        => 2,
                            'favorite_id' => $v['tid'],
                        ];
                        $res = apiCall(FavoritesApi::GET_INFO,[$map]);
                        if(!$res['status']) $this -> apiReturnErr($res['info']);
                        if(!empty($res['info'])) $v['is_fav'] = 1;
                        //用户是否关注
                        $map = [
                            'type'        => 2,
                            'favorite_id' => $v['tid'],
                        ];
                        $v['is_focus'] = apiCall(MemberFocusApi::IS_FOCUS,[$uid,$v['author_id']]);
                    }
                    //点赞信息
                    $v['like_info'] = [];
                    if(intval($max_like)>0){
                        $r = apiCall(ForumPostLikeApi::QUERY_WITH_USER,[['p.tid'=>$v['tid']],['curpage'=>1,'size'=>$max_like],'p.`like_time` desc',false,'p.id,p.uid,p.like_time,m.head,m.nickname,m.sex']);
                        if(!$r['status']) $this->apiReturnErr($r['info']);
                        $v['like_info'] = $r['info']['list'];
                    }
                    //标签信息
                    $v['tag_info'] = apiCall(TagApi::GET_S,[$v['tid']]);
                    //宝宝信息
                    $v['baby_default'] = apiCall(BabyApi::GET_DEFAULT,[$v['author_id']]);
                    //获取回复信息 - 自带评论
                    $v['reply_info']= [];
                    if(intval($max_reply)){
                        $result = apiCall(ForumPostApi::QUERY_POST,array($v['fid'],$v['tid'],1,$max_reply,$max_comment,0));
                        if(!$result['status']) $this -> apiReturnErr($result['info']);
                        $v['reply_info'] = $result['info'];
                        //修复 回复数错误
                        if($result['info'] && intval($result['info']['count']) !== intval($v['replies'])) $v['replies'] = $result['info']['count'];
                    }
                }
                $this -> cache($cacheKey,['count'=>$count,'list'=>$list],10);
            }else{
                $this -> apiReturnErr($result['info']);
            }
        }
    }
    //帖子修改 -暂限时光机 - 9
    public function edit(){
        $this->checkVersion($this->api_ver);
        addLog("ForumThread/edit", $_GET, $_POST, $this->client_id . "调用论坛主题添加接口!");

        if(IS_POST){
            $tid      = $this -> _post('tid',0,'tid缺失');
            $uid      = $this -> _post('uid',0,'uid缺失');
            $subject     = $this -> _post('subject','');
            $message     = $this -> _post('message','');
            $attachments = $this -> _post('attachments','');
            $tags        = $this -> _post('tags','');
            $uid = intval($uid);
            $tid = intval($tid);
            //帖子检测
            $r = apiCall(ForumThreadApi::GET_INFO,[['tid'=>$tid]]);
            $this->checkApiReturn($r,false,'tid错误');
            $fid = intval($r['info']['fid']);
            $author_id = intval($r['info']['author_id']);
            //暂限时光机 - 9
            $r = apiCall(ForumForumApi::GET_FID_WITH_CHILD,[9]);
            if(!$r['status']) $this->apiReturnErr($r['info']);
            if(!in_array($fid,$r['info']))  $this->apiReturnErr('此接口暂限时光机板块使用!');
            //验证板块信息 - 返回是否审核
            if(0 ===$fid) $this->apiReturnErr('该帖板块非法');
            $result  = apiCall(ForumForumApi::CHECK_BLOCK,[$fid]);
            if(!$r['status']) $this->apiReturnErr($r['info']);
            $check = intval($r['info']);

            //验证用户信息
            $res = apiCall(MemberApi::GET_INFO,[['uid'=>$uid]]);
            $this->checkApiReturn($res,false,'非法用户');
            //用户权限检测
            if($author_id == $uid){
                //用户为作者
                //是否为板块 或父板块 管理
                $r = apiCall(ForumUserAdmingroupApi::IS_ADMIN,[$uid,$fid]);
                if(!$r['status']) $this->apiReturnErr($r['info']);
                //非管理用户是否禁言
                if(!$r['info']){
                    $r = apiCall(ForumSilentApi::IS_SILENT,[$uid]);
                    if(!$r['status']) $this->apiReturnErr($r['info']);
                    if($r['info']) $this->apiReturnErr($r['info']);
                }
            }else{
               //用户是否有fid改帖权限
               $r = apiCall(ForumUserAdmingroupApi::HAS_POWER,[$uid,$fid,"ALLOW_EDIT_POST"]);
               if(!$r['status']) $this->apiReturnErr($r['info']);
               if(!$r['info']) $this->apiReturnErr('越权行为');
            }
            // ======================================================
            $thread_entity  = [];
            //关键词过滤
            $subject = trim($subject);
            if($subject){
                $this->filter($subject);
                //标题检测
                $result  = apiCall(ForumThreadApi::GET_INFO,[['subject'=>$subject]]);
                $this->checkApiReturn($result);
                if(!empty($result['info']) && $tid != $result['info']['tid']){
                    $this->apiReturnErr('标题被其他帖子占用');
                }
                $thread_entity['subject'] = $subject;
            }
            if($message){
                $message = $this->filter($message);
                $thread_entity['message'] = $message;
            }
            $ip      = get_client_ip(1);
            $now     = NOW_TIME;
            $model   = new \think\model\Adv();
            $model->startTrans();
            // $status  = (1==$check || (isset($fcheck) && 1==$fcheck))?1:0; //该板块及父板块是否开启审核，
            $status  = (1==$check)?1:0; //该板块是否开启审核，
            if($thread_entity){
                $thread_entity['useip']       = $ip;
                $thread_entity['update_time'] = $now;
                $thread_entity['status']      = $status;
                $result = apiCall(ForumThreadApi::SAVE,[['tid'=>$tid],$thread_entity]);
                $this->checkApiReturn($result,false,false,$model);
            }
            //添加附件 - 图片删除另外接口已做处理
            if($attachments !== ""){
                // trace('=====');
                // trace($attachments);
                // 查询现有 附件
                $r = apiCall(ForumAttachmentApi::QUERY_NO_PAGING,[['tid'=>$tid,'pid'=>0,'uid'=>$author_id]]);
                $this->checkApiReturn($result,false,false,$model);
                $aids_old = [];
                foreach ($r['info'] as $v) {
                   $aids_old[] = $v['id'];
                }
                $aids_old = array_unique($aids_old);
                trace('===');
                trace($aids_old);
                $aids_new = array_unique(explode(',',$attachments));
                trace('===');
                trace($aids_old);
                $aids_add = [];
                foreach($aids_new as $v){
                    //是否存在 $aids_old 中
                    $key = array_search($v, $aids_old);
                    if(false === $key){
                        //need to add
                        $aids_add[] = [
                        'tid' => $tid,
                        'pid' => 0,
                        'uid' => $author_id,
                        'aid' => $v,
                        ];
                    }else{
                        unset($aids_old[$key]);
                    }
                }
                //pic add
                if($aids_add){
                    $result = apiCall(ForumAttachmentApi::ADD_ALL,[$aids_add]);
                    $this->checkApiReturn($result,false,false,$model);
                }
                //pic del
                // trace('===');
                // trace($aids_old);
                if($aids_old){
                    $result = apiCall(ForumAttachmentApi::DELETE,[['_string'=>'`id` in ('.implode(',', $aids_old).')']]);
                    $this->checkApiReturn($result,false,false,$model);
                }
            }
            //添加标签
            if($tags){
                $result = apiCall(TagApi::EDIT_S,[$tags,true,$tid]);
                $this->checkApiReturn($result,false,false,$model);
            }
            $model ->commit();
            $this->apiReturnSuc('修改成功');
        }
    }
    //发帖
    public function add(){
        $this->checkVersion(101);
        addLog("ForumThread/add", $_GET, $_POST, $this->client_id . "调用论坛主题添加接口!");

        if(IS_POST){
            $fid         = $this -> _post('fid',0,'fid缺失');
            $typeid      = $this -> _post('typeid',0);//非板块，热门等。。
            // $author      = $this -> _post('author','','用户昵称参数缺失');
            $author_id   = $this -> _post('author_id',0,'uid缺失');
            $subject     = $this -> _post('subject','');
            $message     = $this -> _post('message','','内容缺失');
            $attachments = $this -> _post('attachments','');
            $tags        = $this -> _post('tags','');
            //发帖间隔判断
            $r = getCacheTree('THREAD_REST',3);
            if(!$r['status']) $this->apiReturnErr($r['info']);
            $rest = (int)$r['info'];
            unset($r);
            $cacheKey = 'threadrest-'.$author_id;
            if(S($cacheKey)){
                $this->apiReturnErr('请保持间隔'.$rest.'秒');
            }
            //去掉宝宝乐 - 4
            // $fid = intval($fid);
            // $r = apiCall(ForumForumApi::GET_FID_WITH_CHILD,[4]);
            // if(!$r['status']) $this->apiReturnErr($r['info']);
            // if(in_array($fid,$r['info']))  $this->apiReturnErr('此接口不适用宝宝乐发布!');
            //验证板块信息
            $r = apiCall(ForumForumApi::CHECK_BLOCK,[$fid]);
            if(!$r['status']) $this->apiReturnErr($r['info']);
            $check = intval($r['info']);
            //验证用户信息
            $res = apiCall(MemberApi::GET_INFO,[['uid'=>$author_id]]);
            $this->checkApiReturn($res,false,'非法用户');
            $author = $res['info']['nickname'];
            // if($res['info']['nickname'] != $author){
            //     $this -> apiReturnErr("信息未及时更新，请重新登录后尝试！");
            // }
            //用户是否禁言
            $r = apiCall(ForumSilentApi::IS_SILENT,[$author_id]);
            if(!$r['status']) $this->apiReturnErr('您已被禁言暂不能发帖');
            if($r['info']) $this->apiReturnErr($r['info']);
            // ======================================================
            //关键词过滤
            $subject = trim($subject);
            if($subject){
                $this->filter($subject);
                //标题检测
                // $result  = apiCall(ForumThreadApi::GET_INFO,[['subject'=>$subject]]);
                // $this->checkApiReturn($result,false,false,false,'同标题已存在');
            }

            $message = $this->filter($message);
            $ip      = get_client_ip(1);
            $now     = NOW_TIME;
            // $status  = (1==$check || (isset($fcheck) && 1==$fcheck))?1:0; //该板块及父板块是否开启审核，
            $status  = (1==$check)?1:0; //该板块是否开启审核，
            $thread_entity = [
                'fid'       => $fid,
                'typeid'    => $typeid,
                // 'author'    => $author,
                'author_id' => $author_id,
                'subject'   => $subject,
                'dateline'  => $now,
                'message'   => $message,
                'useip'     => $ip,
                'update_time'  => $now,
                'views'     => 0,
                'replies'   => 0,
                'digest'    => 0,
                'stick'     => 0,
                'status'    => $status,
                'likes'     => 0,
                'favs'      => 0,
            ];
            $model = new \think\model\Adv();
            $model->startTrans();
            $result = apiCall(ForumThreadApi::ADD,[$thread_entity]);
            $this->checkApiReturn($result,false,false,$model);
            $tid = $result['info'];

            //添加附件
            if($attachments !== ""){
                $aid = explode(',',$attachments);
                $dataList = [];
                $i = 0;
                foreach($aid as $v){
                    $dataList[$i] = [
                        'tid' => $tid,
                        'pid' => 0,
                        'uid' => $author_id,
                        'aid' => $v,
                    ];
                    $i++;
                }
                $result = apiCall(ForumAttachmentApi::ADD_ALL,[$dataList]);
                $this->checkApiReturn($result,false,false,$model);
            }
            //添加标签
            if($tags){
                $result = apiCall(TagApi::ADD_S,[$tags,true,$tid]);
                $this->checkApiReturn($result,false,false,$model);
            }
            //改变版块中帖子数量以及最后发表人
            $result = apiCall(ForumForumApi::UPDATE,[$fid,$author,1]);
            $this->checkApiReturn($result,false,false,$model);

            //+score  +exp
            $result = apiCall(UserLogApi::THREAD_ADD,[$author_id]);
            if(!$result['status']) $this ->apiReturnErr($result['info']);

            $model->commit();
            S($cacheKey,'ing',$rest);
            if(1==$status){
                //需要审核
                $this->apiReturnSuc(['info'=>'发帖成功，等待审核','msg'=>$result['info']]);
            }else{
                $this->apiReturnSuc(['info'=>'发帖成功','msg'=>$result['info']]);
            }
        }else{
            $this->apiReturnErr('错误请求方式');
        }
    }

    //点赞
    public function like(){
        $this->checkVersion(101);
        addLog("ForumThread/like", $_GET, $_POST, $this->client_id . "调用论坛点赞接口!");

        if(IS_POST){
            $tid     = $this->_post('tid',0,'tid缺失');
            $pid     = $this->_post('pid',0);
            $uid     = $this->_post('uid','','用户ID缺失');
            $is_like = $this->_post('like_value',1);
            if(0==$tid && 0==$pid) $this->apiReturnErr('非法点赞');
            $tid = intval($tid);
            $pid = intval($pid);
            // if($tid) $pid = 0;
            //查询是否已点赞
            $map = [
                'pid'     =>$pid,
                'tid'     =>$tid,
                'uid'     =>$uid
            ];
            $result = apiCall(ForumPostLikeApi::COUNT,array($map));
            if($result['status']){
                if($result['info']>0){
                    //已点赞
                    if($is_like==0){
                      //取消点赞
                      $this->apiReturnErr('你不能取消点赞');
                    }else{
                      //点赞
                      $this->apiReturnErr('你已经点过赞了');
                    }

                }else{
                    //未点赞
                    if($is_like==0){
                      //取消点赞
                      $this->apiReturnErr('你未点赞');
                    }else{
                        if($pid){
                            //回复点赞
                            $this->apiReturnErr('回复点赞暂未开放');
                            $r = apiCall(ForumPostApi::GET_INFO,[['tid'=>$tid,'pid'=>$pid],false,'author_id']);
                        }else{
                            //帖子点赞
                            $r = apiCall(ForumThreadApi::GET_INFO,[['tid'=>$tid],false,'author_id']);
                        }
                        if(!$r['status']) $this->apiReturnErr($r['info']);
                        if(empty($r['info'])) $this->apiReturnErr('tid或pid错误');
                        $author_id = $r['info']['author_id'];
                        //点赞
                        $entity = [
                            'pid'       =>$pid,
                            'tid'       =>$tid,
                            'uid'       =>$uid,
                            'author_id' =>$author_id,
                            'like_time' =>NOW_TIME,
                        ];
                        $result = apiCall(ForumPostLikeApi::ADD,array($entity));
                        if(!$result['status']){
                            $this -> apiReturnErr($result['info']);
                        }
                        if($pid){
                            //推送bbs消息
                            $entity = [
                                'from_id' =>0,
                                'title'   =>Message::MESSAGE_BBS,
                                'record'  =>false,
                                'content' =>'您的回复有人点赞了',
                                'summary' =>'您的回复有人点赞了',
                                'extra'   =>'', //消息记录中的
                            ];
                            $after_open = ['type'=>'go_activity','param'=>Message::MESSAGE_BBS_ACTIVITY,'extra'=>['type'=>2]]; //推送参数
                            $r = apiCall(MessageApi::PUSH_MESSAGE_WITH_TYPE,[Message::MESSAGE_CALL,$entity,$author_id,false,$after_open]);
                            //回复点赞数+1
                            apiCall(ForumPostApi::SET_INC,[['pid'=>$pid,'tid'=>$tid],'likes',1]);
                            if(!$r['status']) $this->apiReturnSuc('点赞成功!');
                        }else{
                            //推送bbs消息
                            $entity = [
                                'from_id' =>0,
                                'title'   =>Message::MESSAGE_BBS,
                                'content' =>'您的帖子有人点赞了',
                                'summary' =>'您的帖子有人点赞了',
                                'record'  =>false,
                                'extra'   =>'', //消息记录中的
                            ];
                            $after_open = ['type'=>'go_activity','param'=>Message::MESSAGE_BBS_ACTIVITY,'extra'=>['type'=>2]]; //推送参数
                            $r = apiCall(MessageApi::PUSH_MESSAGE_WITH_TYPE,[Message::MESSAGE_CALL,$entity,$author_id,false,$after_open]);
                            //帖子点赞数+1
                            apiCall(ForumThreadApi::SET_INC,[['tid'=>$tid],'likes',1]);
                            if(!$r['status']) $this->apiReturnSuc('点赞成功!');
                        }
                        $this -> apiReturnSuc('点赞成功!');
                    }
                }
            }else{
                $this -> apiReturnErr($result['info']);
            }
            // $map = array(
            //     'tid' => $tid,
            // );
            // $field = "likes";

            // $result = apiCall(ForumThreadApi::SET_INC,array($map,$field));
            // if($result['status']){
            //     $this -> apiReturnSuc('点赞成功!');
            // }else{
            //     $this -> apiReturnErr($result['info']);
            // }

        }

    }

    //加精
    public function digest(){
        $this->checkVersion($this->api_ver);
        addLog("ForumThread/digest", $_GET, $_POST, $this->client_id . "调用论坛主题帖加精接口!");

        if(IS_POST){

            $uid = $this -> _post('uid',0,'用户id缺失');
            $tid = $this -> _post('tid',0,'缺少主题id');
            $digest_value = $this -> _post('digest_value',-1,'缺少digest_value参数');
            $digest_value = intval($digest_value);
            if(!in_array($digest_value, [0,1])){
                $this -> apiReturnErr('digest_value参数错误');
            }

            $result = apiCall(ForumThreadApi::DIGEST,array($uid,$tid,$digest_value));
            if($result['status']){
                $this -> apiReturnSuc($result['info']);
            }else{
                $this -> apiReturnErr($result['info']);
            }

        }

    }

    //TODO 限制置顶主题个数
    public function stick(){
        $this->checkVersion($this->api_ver);
        addLog("ForumThread/stick", $_GET, $_POST, $this->client_id . "调用论坛主题帖置顶接口!");

        if(IS_POST){
            $uid = $this -> _post('uid',0,'缺少uid参数');
            $tid = $this -> _post('tid',0,'缺少tid参数');
            $stick_value = $this -> _post('stick_value',-1,'缺少stick_value参数');

            if(!in_array($stick_value,[0,1]))
                $this -> apiReturnErr('stick_value参数错误');
            $result = apiCall(ForumThreadApi::STICK,array($uid,$tid,$stick_value));
            if($result['status']){
                $this -> apiReturnSuc($result['info']);
            }else{
                $this -> apiReturnErr($result['info']);
            }

        }

    }

    /**
     * 查询用户信息
     */
    private function getUserInfo($uid){
        $r = apiCall(BbsMemberApi::GET_USER_INFO,[$uid,true,false,false,false]);
        if($r['status']){
            return $r['info'];
        }else{
            return [];//$this->apiReturnErr('查询用户信息失败'.$uid);
        }
        // $r = apiCall(MemberApi::GET_INFO,array($uid));
        // if($r['status'] && $r['info']){
        //     return $r['info'];
        // }else{
        //     $this->apiReturnErr('查询用户信息失败');
        // }
    }

    /**
     * 关键词过滤
     */
    private function filter($posts){
        $result = apiCall(FilterKeyWordsApi::FILTER,[$posts]);
        return $result['info'];
    }

    /**
     * utf8-转unicode
     */
    public function unicode_encode($text){
        $str = json_encode($text);
        $str = str_replace("\"", "", $str);

        return $str;
    }

    /**
     * unicode-转utf8
     */
    public function unicode_decode($str){
        $str = "\"$str\"";
        $text = "{\"text\":".$str."}";
        $arr = json_decode($text,true);
        return $arr['text'];


    }

    /**
     * 查询用户头像
     */
    private function getUserHeadByID($uid){
        $r = apiCall(BbsMemberApi::GET_USER_INFO,array($uid,false,false,false,false));
        if($r['status'] && $r['info']){
            return $r['info']['head'];
        }else{
            return '0';//$this->apiReturnErr('查询用户信息失败');
        }
    }

    /**
     * [checkApiReturn description] domain专用
     * @author rainbow
     * @param  [type]  $result  [description]
     * @param  string  $err     [description]
     * @param  string  $nullerr [description]
     * @param  boolean $model   事务对象
     * @param  string  $fullerr [description]
     * @return [type]           [description]
     */
    private function checkApiReturn($result,$err=false,$nullerr=false,$model=false,$fullerr=false)
    {
        if(false === $result['status']){
            if(false === $err) $err = $result['info'];
            if(false !== $model) $model->rollback();
            $this->apiReturnErr($err);
        }else{
            if(false !== $nullerr && empty($result['info'])){
                if(false !== $model) $model->rollback();
                $this->apiReturnErr($nullerr);
            }
            if(false !== $fullerr && !empty($result['info'])){
                if(false !== $model) $model->rollback();
                $this->apiReturnErr($fullerr);
            }
        }
    }
}